package com.fp.m7.client.presenter;

import java.util.List;

import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.place.PlaceRequest;
import net.customware.gwt.presenter.client.place.TokenFormatter;
import net.customware.gwt.presenter.client.widget.WidgetDisplay;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;

import com.allen_sauer.gwt.log.client.Log;
import com.fp.m7.client.place.ProfilePlace;
import com.fp.m7.client.widget.UserSimpleWidget;
import com.fp.m7.shared.Constants;
import com.fp.m7.shared.dto.UserDto;
import com.fp.m7.shared.services.AccountServiceAsync;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.inject.Inject;

/**
 * Home presenter's display is supposed to handle presenting random users list.
 * 
 * @author 7
 */
public class HomePresenter extends WidgetPresenter<HomePresenter.Display> {

    public interface Display extends WidgetDisplay {

        HasWidgets getContentPanel();

    }

    private TokenFormatter tokenFormatter;
    private AccountServiceAsync accountService;

    @Inject
    public HomePresenter(Display display, EventBus eventBus, //
            TokenFormatter tokenFormatter, //
            AccountServiceAsync accountService) {
        super(display, eventBus);

        this.tokenFormatter = tokenFormatter;
        this.accountService = accountService;
    }

    @Override
    protected void onBind() {
    }

    @Override
    protected void onUnbind() {
    }

    @Override
    protected void onRevealDisplay() {
        accountService.getRandomUsers(Constants.RANDOM_USERS_COUNT, new AsyncCallback<List<UserDto>>() {
            @Override
            public void onSuccess(List<UserDto> users) {
                if (users != null) {
                    display.getContentPanel().clear();
                    
                    for (UserDto user : users) {
                        PlaceRequest req = new PlaceRequest(ProfilePlace.NAME) //
                                .with(ProfilePlace.NICKNAME, user.getNickname());

                        UserSimpleWidget userWidget = new UserSimpleWidget();
                        userWidget.setContents(user.getNickname(), tokenFormatter.toHistoryToken(req),
                                user.getAvatarUrl());

                        display.getContentPanel().add(userWidget);
                    }

                }
            }

            @Override
            public void onFailure(Throwable throwable) {
                Log.info("Picking random users went wrong...", throwable);
                display.getContentPanel().clear();
            }
        });
    }

}
